import { useCallback, useLayoutEffect, useRef, useReducer, useMemo } from 'react';
export const useGetSet = <T>(initialState:T):[() => T,(s:T) => void] => {
    const state = useRef<T>(initialState);
    const [,update] = useReducer(() => Object.create(null),{});
    const updateState = (newState: T) => {
        state.current = newState;
        update();
    }
    return useMemo(() => [
        () => state.current,
        updateState
    ],[])
}
const useIsScroll = <T extends HTMLElement>(el: Window | T | (() => T) = window,throlleTime:number = 300): boolean => {
    const [isScroll,setIsScroll] = useGetSet(false);
    const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
    const onScrollHandler = useCallback(() => {
        setIsScroll(true);
        if(timer.current){
            clearTimeout(timer.current);
        }
        // https://stackoverflow.com/questions/4620906/how-do-i-know-when-ive-stopped-scrolling
        timer.current = setTimeout(() => {
            setIsScroll(false);
        },throlleTime)
    },[])
    useLayoutEffect(() => {
        const ele = typeof el === 'function' ? el() : el;
        if(!ele){
            return;
        }
        ele.addEventListener('scroll',onScrollHandler,false);
        return () => {
            ele.removeEventListener('scroll',onScrollHandler,false);
        }
    },[]);
    return isScroll();
}

export default useIsScroll